﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Reactive.Linq;
using System.Text;
using System.Threading;
using CameraViewer.Model;
using MiscUtil;
using System.Reactive;

namespace CameraViewer
{
    class VehmonUpdater
    {
        private int _stationId;
        public event EventHandler<MiscUtil.EventArgs<Model.TogVehmon>> NewLprFound;


        protected virtual void OnNewLprFound(EventArgs<TogVehmon> e)
        {
            EventHandler<EventArgs<TogVehmon>> handler = NewLprFound;
            if (handler != null) handler(this, e);
        }

        public void Start(int stationId)
        {
            if (_timer == null)
            {
                _stationId = stationId;
                _timer = new Timer(LoadNext, null, TimeSpan.FromSeconds(0), TimeSpan.FromMinutes(1));
            }
        }

        public void Stop()
        {
            if (_timer != null)
            {
                _timer.Dispose();
                _timer = null;
            }
        }

        private int _isLoading;
        private Timer _timer;

        private void LoadNext(object i)
        {
            if (System.Threading.Interlocked.Exchange(ref _isLoading, 1) == 0)
            {
                try
                {

                    System.Diagnostics.Debug.WriteLine("begin query");
                    var res = Repository.Instance.GetNextTogVehmon("KKBH = ?", _stationId);
                    if (res != null)
                    {
                        OnNewLprFound(new EventArgs<TogVehmon>(res));
                    }

                    System.Diagnostics.Debug.WriteLine("end query");

                }
                catch (Exception)
                {

                }
                finally
                {
                    System.Threading.Interlocked.Exchange(ref _isLoading, 0);
                }
            }

        }

    }
}
